package com.dengcj.ecology.request;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

import java.util.*;

/**
 * @author dengchunjie
 * @Description: 通过EcologyPlugin处理的通用节点处理类
 * @date 2022/1/12 18:55
 */
public class CommonNodeActionForPlugin extends BaseBean implements Action {

    // EcologyPlugin上的功能实现类
    private String pluginclass;

    // EcologyPlugin的项目根路径
    private String pluginurl;

    public String getPluginclass() {
        return pluginclass;
    }

    public void setPluginclass(String pluginclass) {
        this.pluginclass = pluginclass;
    }

    public String getPluginurl() {
        return pluginurl;
    }

    public void setPluginurl(String pluginurl) {
        this.pluginurl = pluginurl;
    }

    @Override
    public String execute(RequestInfo requestInfo) {

        try {
            JSONObject jsonObject = new JSONObject();

            // EcologyPlugin执行类 以参数形式传入
            jsonObject.set("classpath", pluginclass);
            // 工作流请求ID
            jsonObject.set("requestid", requestInfo.getRequestid());
            // 工作流ID
            jsonObject.set("workflowid", requestInfo.getWorkflowid());
            // 节点ID
            jsonObject.set("nodeid", requestInfo.getRequestManager().getNodeid());
            // 创建人Id
            jsonObject.set("creator", requestInfo.getRequestManager().getCreater());
            // 动作来源 submit为提交，reject为退回
            jsonObject.set("src", requestInfo.getRequestManager().getSrc());
            // 单据表名
            jsonObject.set("tablename", requestInfo.getRequestManager().getBillTableName());
            // 签字意见
            jsonObject.set("requestlog", requestInfo.getRequestLog());
            // 请求创建日期
            jsonObject.set("createdate", requestInfo.getRequestManager().getCreatedate());
            // 请求创建时间
            jsonObject.set("createtime", requestInfo.getRequestManager().getCreatetime());
            // 最后节点ID
            jsonObject.set("lastnodeid", requestInfo.getRequestManager().getLastNodeid());
            // 下一节点ID
            jsonObject.set("nextnodeid", requestInfo.getRequestManager().getNextNodeid());
            // 下一节点类型
            jsonObject.set("nextnodetype", requestInfo.getRequestManager().getNextNodetype());
            // 请求名称
            jsonObject.set("requestname", requestInfo.getRequestManager().getRequestname());
            // 当前节点操作者
            jsonObject.set("userid", requestInfo.getRequestManager().getUserId());

            Map<String, String> mainFormMap = getMainFormMap(requestInfo);
            Map<String, List<Map<String, String>>> detailFormMap = getDetailFormMap(requestInfo);

            // 主表数据
            jsonObject.set("maindata", new JSONObject(JSONUtil.parseObj(mainFormMap)));
            // 明细表数据
            jsonObject.set("detaildata", new JSONObject(JSONUtil.parseObj(detailFormMap)));

            String ecologyPluginApi = "";
            if(StrUtil.isNotBlank(pluginurl)){
                ecologyPluginApi = pluginurl;
            } else {
                // 从/ecology/WEB-INF/prop/EcologyPlugin.properties中读取外挂程序接口地址
                ecologyPluginApi = this.getPropValue("EcologyPlugin","NodeActionApi");
            }

            if(StrUtil.isBlank(ecologyPluginApi)){
                requestInfo.getRequestManager().setMessage("获取EcologyPlugin接口失败");
                requestInfo.getRequestManager().setMessagecontent("请联系管理员检查配置文件或在接口类中指定参数");
                return Action.FAILURE_AND_CONTINUE;
            }

            String result = HttpRequest.post(ecologyPluginApi)
                    .body(jsonObject.toString())
                    .timeout(15000)
                    .execute().body();


            if(!JSONUtil.isJson(result)){
                requestInfo.getRequestManager().setMessage("EcologyPlugin执行过程中发生异常");
                requestInfo.getRequestManager().setMessagecontent("请查看EcologyPlugin日志，异常信息："+result);
                return Action.FAILURE_AND_CONTINUE;
            }
            JSONObject resultJson = new JSONObject(result);
            if(!resultJson.getBool("status")){
                requestInfo.getRequestManager().setMessage("节点附加操作执行失败");
                requestInfo.getRequestManager().setMessagecontent(resultJson.getStr("msg"));
                return Action.FAILURE_AND_CONTINUE;
            }
        } catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessage("节点附加操作执行发生异常");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 从Requestinfo对象中获取主表数据，返回Map
     * 通过mainFormMap.get("主表字段名")获取值
     * @param requestInfo 请求对象
     * @return 主表Map
     */
    private Map<String, String> getMainFormMap(RequestInfo requestInfo){
        Map<String, String> mainFormMap = new HashMap<>();
        Arrays.stream(requestInfo.getMainTableInfo().getProperty()).forEach(property -> mainFormMap.put(property.getName(), Util.null2String(property.getValue())));

        return mainFormMap;
    }

    /**
     * 从Requestinfo对象中获取明细表数据
     * 获取明细表1的数据使用示例：
     * Map<String, List<Map<String, String>>> detailFormMap = NodeActionUtil.getDetailFormMap(requestInfo);
     * List<Map<String, String>> dt1List = detailFormMap.get("dt1");
     * dt1List.forEach(map->{
     *     String content = map.get("content");
     * });
     * @param requestInfo 请求对象
     * @return 所有明细表数据
     */
    private Map<String, List<Map<String, String>>> getDetailFormMap(RequestInfo requestInfo){
        Map<String, List<Map<String, String>>> detailFormMap = new HashMap<>();
        DetailTable[] detailTables = requestInfo.getDetailTableInfo().getDetailTable();
        int detailTableLength = detailTables.length;
        for (int i=0 ;i < detailTableLength; i++) {
            DetailTable detailTable = detailTables[i];
            Row[] rows = detailTable.getRow();
            List<Map<String, String>> rowList = new ArrayList<>();
            for (Row row : rows) {
                Cell[] cells = row.getCell();
                Map<String, String> dtRowMap = new HashMap<>();
                for (Cell cell : cells) {
                    dtRowMap.put(cell.getName(), Util.null2String(cell.getValue()));
                }

                rowList.add(dtRowMap);
            }

            detailFormMap.put("dt"+(i+1), rowList);
        }

        return detailFormMap;
    }
}
